package com.cos.shop.service.impl;

import com.cos.shop.common.Const;
import com.cos.shop.common.ResponseResult;
import com.cos.shop.dao.UserDao;
import com.cos.shop.dao.impl.UserDaoImpl;
import com.cos.shop.entity.User;
import com.cos.shop.service.UserServices;
import com.cos.shop.util.*;

import java.sql.SQLException;

/**
 * Copyright (C),2021-2022,亚瑟王
 * FileName: UserServicesImpl
 * Author: saber
 * Date:2022/9/16 18:36
 */
public class UserServicesImpl implements UserServices {
    private UserDao ud = new UserDaoImpl();

    @Override
    public ResponseResult doLogin(String username, String password) {
        try {
            if (StringUtils.isNotEmpty(username,password)){
                User user =ud.getUserByUname(username);

                if (user!=null&&user.getUpassword().equals(MD5Utils.md5(password))){
                    if(user.getUstatus()==Const.UserCode.NOT_ACTIVE){
                        return ResponseResult.createFail("账户还没激活,请先激活!!!");
                    }
                    return ResponseResult.createSuccess(user);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.createFail("用户名或密码错误");
    }

    @Override
    public boolean register(User u) {
        try {
            u.setUcode(RandomUtils.createActive());
            u.setUrole(Const.UserCode.COMMON_USER);
            u.setUstatus(Const.UserCode.NOT_ACTIVE);
            u.setUpassword(MD5Utils.md5(u.getUpassword()));

            if (ud.addUser(u)>0) {
                new Thread(()-> EmailUtils.sendEmail(u)).start();
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public User checkUserName(String username) {
        try {
            if (StringUtils.isNotEmpty(username)) {
                return ud.getUserByUname(username);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public ResponseResult doActivate(String e, String c) {
        try {
            String email = Base64Utils.decode(e);

            String code = Base64Utils.decode(c);

            User user = ud.getUserByEmailAndCode(email,code);

            if (user==null) {
                return ResponseResult.createFail("用户名不存在，无法激活，请先注册");
            }
            if(user.getUstatus() == Const.UserCode.IS_ACTIVE){
                return ResponseResult.createFail("账号已激活，请直接登入");
            }

            int i =ud.changeUserStatus(user.getUid(),Const.UserCode.IS_ACTIVE);

            if (i>0) {
                return ResponseResult.createSuccess("激活成功,请登录！");
            }

        } catch (Exception e1) {
            e1.printStackTrace();
        }

        return ResponseResult.createFail("激活失败,请稍后再试");
    }
}
